package org.epidroid.epidroid.news.utils;

import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;

public class TextFormater {

	private static int[] _colors = { 0xffaaaaaa, 0xff888888, 0xff666666,
			0xff444444 };
	private static int[] _marksColors = { Color.CYAN, Color.YELLOW,
			Color.MAGENTA, Color.GREEN, Color.BLUE };
	private static int _signColor = 0xff444444;

	public static Spannable formatArticle(String text) {
		String[] lines = text.split("\n");
		SpannableStringBuilder builder = new SpannableStringBuilder();

		boolean isSign = false;

		for (String line : lines) {
			line += "\n";

			if (line.regionMatches(0, "-- ", 0, 3)) {
				isSign = true;
			}

			if (isSign)
				formatArticleSign(line, builder);
			else
				formatArticleLine(line, builder);
		}

		return builder;
	}

	private static void formatArticleSign(String line,
			SpannableStringBuilder builder) {
		SpannableStringBuilder subBuilder = new SpannableStringBuilder(line);
		subBuilder.setSpan(new ForegroundColorSpan(_signColor), 0,
				line.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		builder.append(subBuilder);
	}

	private static void formatArticleLine(String line,
			SpannableStringBuilder builder) {
		SpannableStringBuilder subBuilder = new SpannableStringBuilder(line);

		int indentLevel = getIndentLevel(line);
		if (indentLevel > 0) {
			int color = getIndentColor(indentLevel);
			int markColor = getMarkColor(indentLevel);
			subBuilder.setSpan(new ForegroundColorSpan(markColor), 0,
					indentLevel, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			subBuilder.setSpan(new ForegroundColorSpan(color), indentLevel + 1,
					line.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

		}

		builder.append(subBuilder);
	}

	private static int getIndentLevel(String line) {
		int i = 0;
		while ((i < line.length()) && (line.charAt(i) == '>')) {
			i++;
		}
		return i;
	}

	private static int getIndentColor(int indentLevel) {
		indentLevel--;
		if (indentLevel < _colors.length) {
			return _colors[indentLevel];
		} else {
			return _colors[_colors.length - 1];
		}
	}

	private static int getMarkColor(int indentLevel) {
		indentLevel--;
		if (indentLevel < _marksColors.length) {
			return _marksColors[indentLevel];
		} else {
			return _marksColors[_marksColors.length - 1];
		}
	}

}
